import React, { Component } from 'react'
import { connect } from 'react-redux'
import { actions } from '../store/cart'
import { bindActionCreators } from 'redux'

class ShopItem extends Component {
  addCartFn = (shop) => this.props.addCart(shop)

  render() {
    const { itemData } = this.props
    return (
      <div className='shop-item-box'>
        <img className='shop-img' src={itemData.pic}/>
        <div className='right-text'>
          <div className='title'>{itemData.name}</div>
          <div className='price-box'>
            <span>{itemData.price}<b>￥</b></span>
            <button onClick={() => this.addCartFn(itemData)}>购买</button>
          </div>
        </div>
      </div>
    )
  }
}

function mapStateFromProps (state) {
  // 获取 store state 中所有数据，并转成当前组件的 props
  return state.cartStore  // 只分发 cartStore
}

function mapDispatchFromProps (dispatch) {
  // 发送 actions 中的 action
  // 将 actions 中的方法绑定在组件身上，转成 props
  return bindActionCreators(actions, dispatch)

}

export default connect(mapStateFromProps,mapDispatchFromProps)(ShopItem)